#include <iostream>
#include "tcp_server_libevent.h"
#include "winsock2.h"
#include <stdio.h>
#include <thread>
#include <stdlib.h>
#include <functional>

int main() {
  WORD wdVersion = MAKEWORD(2, 2);   //定义自己需要的网络库版本，这里是2.2
  WSADATA wdSockMsg;//这是一个结构体
  int nRes = WSAStartup(wdVersion, &wdSockMsg);//打开一个套接字
  if (0 != nRes) {
		switch (nRes) {
			case WSASYSNOTREADY:
				printf("check your library");
			break;
			case WSAVERNOTSUPPORTED:
				printf("need updated");
				break;
			case WSAEINPROGRESS:
				printf("need reboot");
				break;
			case WSAEPROCLIM:
				printf("WSAEPROCLIM");
				break;
		}
  }
	if (2 != HIBYTE(wdSockMsg.wVersion) || 2 != LOBYTE(wdSockMsg.wVersion)) {
	  printf("WSACleanup");
	  WSACleanup();
	  return 0;
  }
  std::cout<<"start server libevent\r\n";
  TcpServerLibevent server(8021,"127.0.0.1");
  server.SetNewConnectionHandle(
		[&server] (struct bufferevent *ev,uint32_t fd,struct sockaddr_in *p1)
		{
				char*p = inet_ntoa((in_addr)(p1->sin_addr));
				std::cout<<"new client fd " << fd << " from address "<< p <<std::endl;
				auto ret = new ConnectionLibevent(ev,fd,p1);
				// server.AddConnection(fd,ret);
				return ret;
		}
	);
  server.StartServerAndRunSync();
  while(true){
	  Sleep(100);
  }
}